<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Upload extends CI_Controller {

	// public function __construct()
	// {
	// 	$this->load->model('user_model');
	// }

	private function check_token($key)
    {
        $token = md5($this->config->item('encryption_key').$key);
        return $token == $_POST['token'] ? true : false;
    }

	/**
    *上传图片
    * $type: 控件id
    */
    public function uploadimg() 
    {
    	$timestamp = $_POST['timestamp'];
        $uid = (int)$_POST['uid'];
        $type = $_POST['type'];
        $uploadName = $type."_upload";
        if (isset($_FILES['Filedata']) && $_FILES['Filedata']['name'] && $this->check_token($timestamp))
        {
            $config = array();
            $config['upload_path'] = "upload/$type/".date('Ym');
            $config['allowed_types']= '*';	//jpg|png|jpeg
            $config['max_size']     = 1500;
            $config['overwrite']    = true;
            $config['file_name']    = $type.'_'.$uid.'_'.time();
            mkpath($config['upload_path']);
            $this->load->library('upload', $config);
            if ( ! $this->upload->do_upload('Filedata')){
                $error = $this->upload->display_errors();
                echo '100|'.strip_tags($error);exit;
            }
            else{
                //裁剪后上传OSS
                $this->upload->cropUpload();
                
                $upload_data = $this->upload->data();
                // $this->load->model('Attach_model');
                // $map = array(
                //   'attach_type'=>$this->router->fetch_method(),
                //   'uid'=>$uid,
                //   'ctime'=>$this->timestamp,
                //   'name'=>$upload_data['client_name'],
                //   'type'=>$upload_data['file_type'],
                //   'size'=>$upload_data['file_size'],
                //   'extension'=>$upload_data['file_ext'],
                //   'save_path'=>$config['upload_path'],
                //   'save_name'=>$upload_data['orig_name'],
                //   'ip'=>$this->input->ip_address(),
                // );
                // $aid = $this->Attach_model->insert($map);
                $pic  = $config['upload_path'].'/'.$upload_data['file_name'];
            }
            if ($pic){
                   echo '200|'.$pic;exit;
            }
        }   
    }
    
    //上传图片（裁剪）
    public function catupload()
    {
    	//提交处理
    	if ($this->input->is_post())
    	{
    		//上传原图
    		$path = "./upload/showimg/".date('Ym', time()).'/';
    		$this->_make_directory($path); //没有就创建
    		$pic_config['upload_path'] = $path;
    		$pic_config['allowed_types'] = 'gif|jpg|png';
    		$pic_config['file_name'] = 'showimg_'.$this->loginID.'_'.time().'.jpg'; //重新命名
    	
    		$this->load->library('upload', $pic_config);
    		if(!$this->upload->do_upload('cover'))
    		{
    			$error[] = $this->upload->display_errors();
    			exit;
    		}
    	
    		//图片处理
    		$img_data = $this->upload->data();
    		//1. 缩小
//     		$pic_config['image_library'] = 'gd2';
//     		$pic_config['source_image'] = $img_data['full_path'];
//     		$pic_config['maintain_ratio'] = TRUE;
//     		$pic_config['width'] = $this->input->post('width');  //头像框中最大宽度的像素
//     		$pic_config['height'] = $this->input->post('height'); //头像框中最大高度的像素
//     		$this->load->library('image_lib', $pic_config);
//     		if(!$this->image_lib->resize()) {
//     			$error[] = $this->image_lib->display_errors();
//     		}
    		 
    		//宽度比例
    		if ($this->input->post('width') > $this->input->post('rel_width')) 
    		{
    			$rate_width = $this->input->post('width')/$this->input->post('rel_width');
    		}
    		else
    		{
    			$rate_width = $this->input->post('rel_width')/$this->input->post('width');
    		}
    		//高度比例
    		if ($this->input->post('height') > $this->input->post('rel_height'))
    		{
    			$rate_height = $this->input->post('height')/$this->input->post('rel_height');
    		}
    		else
    		{
    			$rate_height = $this->input->post('rel_height')/$this->input->post('height');
    		}
    		//2. 裁剪
    		$img_config['source_image'] = $img_data['full_path']; //全路径
    		$img_config['x_axis'] = $this->input->post('left')*$rate_width;
    		$img_config['y_axis'] = $this->input->post('top')*$rate_height;
    		$img_config['width'] = ($this->input->post('right') - $this->input->post('left'))*$rate_width; //宽度
    		$img_config['height'] = ($this->input->post('bottom') - $this->input->post('top'))*$rate_height; //高度
    		$img_config['maintain_ratio'] =  false;
    	
//     		$this->image_lib->initialize($img_config);
    		$this->load->library('image_lib', $img_config);
    		if (!$this->image_lib->crop())
    		{
    			$error[] =  $this->image_lib->display_errors();
    		}
    		
    		$filename = $path.$pic_config['file_name'];
    		
    		//裁剪后上传OSS
    		$this->upload->cropUpload();
    		
    		if ($filename)
    			echo '200|'.$filename;exit;
    	}
    }

    public function uploadvideo() 
    {
        $timestamp = $_POST['timestamp'];
        $uid = (int)$_POST['uid'];
        $type = $_POST['type'];
        $uploadName = $type."_upload";
        if (isset($_FILES['Filedata']) && $_FILES['Filedata']['name'] && $this->check_token($timestamp))
        {
            $config = array();
            $config['upload_path'] = "upload/$type/".date('Ym');
            $config['allowed_types']= '*';  //flv
            $config['max_size']     = 1500;
            $config['overwrite']    = true;
            $config['file_name']    = $type.'_'.$uid.'_'.time();
            mkpath($config['upload_path']);
            $this->load->library('upload', $config);
            if ( ! $this->upload->do_upload('Filedata')){
                $error = $this->upload->display_errors();
                echo '100|'.strip_tags($error);exit;
            }
            else{
                
                //裁剪后上传OSS
                $this->upload->cropUpload();
                
                $upload_data = $this->upload->data();
                $pic  = $config['upload_path'].'/'.$upload_data['file_name'];
            }
            if ($pic){
                   echo '200|'.$pic;exit;
            }
        }   
    }

    public function uploadphotoimg(){
        $timestamp = $_POST['timestamp'];
        $uid = _get_key_val( $_POST['uid'] ,true, false);
        if(!$uid)
            $uid = (int)$_POST['uid'];
        
        //上传一张相册可获得5魔币
        //用户信息
        $this->load->model('User_model');
        $userModel = $this->User_model->get_by_id($uid);
        if ($userModel)
        {
            if ($userModel['insid'])
            {
                $this->load->service('magic_service');
                $this->magic_service->recordMagicCoins($userModel['insid'],5,6);
            }
            else
            {
                $this->load->service('magic_service');
                $this->magic_service->recordMagicCoins($uid,5,6);
            }
        }
        
        $type = $_POST['type'];
        $albumid = isset($_POST['albumid'])?_get_key_val($_POST['albumid'],true, false):0;
        $uploadName = $type."_upload";

        if(!$albumid)
        {
            echo '100|'.strip_tags('请选择相册');exit;
        }
        if (isset($_FILES['Filedata']) && $_FILES['Filedata']['name'] && $this->check_token($timestamp))
        {
            $config = array();
            $config['upload_path'] = "upload/$type/".date('Ym');
            $config['allowed_types']= '*';	//jpg|png|jpeg
            $config['max_size']     = 1500;
            $config['overwrite']    = true;
            $config['file_name']    = $type.'_'.$uid.'_'.time().'_'.rand(0,1000);
            mkpath($config['upload_path']);
            $this->load->library('upload', $config);
            if ( ! $this->upload->do_upload('Filedata')){
                $error = $this->upload->display_errors();
                echo '100|'.strip_tags($error);exit;
            }
            else{
                
                //裁剪后上传OSS
                $this->upload->cropUpload();
                
                $upload_data = $this->upload->data();
                $imgurl = '/'.$config['upload_path'].'/'.$upload_data['file_name'];
                
                $map = array(
                  'albumid'=>$albumid,
                  'userid'=>$uid,
                  'insid'=>$this->loginInsID,
                  'addtime'=>$this->timestamp,
                  'title'=>$upload_data['client_name'],
                  'size'=>$upload_data['file_size'],
                  'ext'=>$upload_data['file_ext'],
                  'img'=>$imgurl,
                  'status'=>1,
                  'ip'=>$this->input->ip_address(),
                );
                $this->load->model('Photo_model');
                $aid = $this->Photo_model->insert_ignore($map);
                $this->load->service('num_service');
                $this->num_service->set_album_photo_num($uid, 'photonum', $albumid);
                
                // 获取相册信息
                $this->load->model('Album_model');
                $albumidInfo = $this->Album_model->get_by_id($albumid);
                //当相册没有封面的时候更新
                if (!$albumidInfo['showimg']) {
                    // 只有系统默认才更新
                    $this->Album_model->update_by_where(array('id'=>$albumid),array('showimg'=>$imgurl));
                }
                $pic  = $imgurl;
                $name = $map['title'];
            }
            if ($pic){
                   echo '200|'.$pic.'|'.$name.'|'.$aid;exit;
            }
        }   
    }
    
    //创建目录
    private function _make_directory($directoryName) {
    	$directory_name = str_replace("\\","/",$directoryName);
    	$dirNames = explode('/', $directory_name);
    	$total = count($dirNames) ;
    	$temp = '';
    	for($i=0; $i<$total; $i++) {
    		$temp .= $dirNames[$i].'/';
    		if (!is_dir($temp)) {
    			$oldmask = umask(0);
    			if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");
    			umask($oldmask);
    		}
    	}
    	return true;
    }
    
    //视频上传
    public function uploadvedio()
    {
    	set_time_limit(0);
    	$targetFolder = '/uploads';
    	if (isset($_FILES['Filedata']) && $_FILES['Filedata']['name'] && $this->check_token($_POST['timestamp'])) {

            //改用CI的上传类来处理视频文件上传
            $config = array();
//             $config['upload_path'] = "{$targetFolder}/{$_POST['usertype']}/";
            $config['upload_path'] = "upload/video/";
            $config['allowed_types']= 'mp4|avi';	//jpg|png|jpeg
            $config['max_size']     = 100000;//100M, 但还要看php.ini里设置的文件大小
            $config['overwrite']    = true;
            $config['file_name']    = $_POST['uid'].'_'.time();
            mkpath($config['upload_path']);
            $this->load->library('upload', $config);
            if ( ! $this->upload->do_upload('Filedata')){
                $error = $this->upload->display_errors();
                echo '100|'.strip_tags($error);exit;
            }
            else {
                
                //裁剪后上传OSS
                $this->upload->cropUpload();
                
                $upload_data = $this->upload->data();
                echo '200|'.$config['upload_path'].$upload_data['file_name'];
            }
            exit;

            $tempFile = $_FILES['Filedata']['tmp_name'];
    		//设置上传文件类型
    		$fileTypes = array('mp4','avi'); // File extensions
    		$fileParts = pathinfo($_FILES['Filedata']['name']);
    		$fileParts['extension'] = strtolower($fileParts['extension']);
    		if (in_array($fileParts['extension'],$fileTypes)) {
    			$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
    			$targetFile = rtrim($targetPath,'/') . '/' . $_POST['usertype'].'/';
    			$newFileName = $_POST['uid'].'_'.time().'.'.$fileParts['extension'];
    			$targetFolder = $targetFolder.'/'.$_POST['usertype'].'/'.$newFileName;
    			//创建文件夹并设置权限
    			if (!file_exists($targetFile))
    			{
    				mkdir($targetFile);
    				chmod($targetFile, 0777);
    			}
    			//新文件路径
    			$targetFile .= $newFileName;
    			if (!(move_uploaded_file($tempFile,$targetFile) && file_exists($targetFile))) {//上传失败
                    echo '100|failed to upload file.';
                } else {
                    echo '200|'.$targetFolder;
                }
                exit;
    		} else {
    			echo '100|Invalid file type.';
    		}
    	}
    }
}